﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Data.Entity;
using EFCachingProvider.Caching;
using Wedo.Domain.Models;
using EFCachingProvider;
using System.ComponentModel.DataAnnotations;

namespace Wedo.Recognition.Repository
{
    public class CachedRepository<TEntity> : GenericRepository<TEntity>, IRepository<TEntity>
     where TEntity : class
    {
       
        protected ICache _Cache;

        /// <summary>
        /// 获取缓存 变化关键字
        /// 表数据变化时触发
        /// </summary>
        /// <returns></returns>
        protected string GetCacheKey()
        {
            return typeof(TEntity).Name;
        }

        public CachedRepository(DbContext dbContext)
            : base(dbContext)
        {
            _Cache = EFCachingProviderConfiguration.DefaultCache;
        }

        public override IQueryable<TEntity> All()
        {
            return CachedAll().AsQueryable();
        }

        public List<TEntity> CachedAll()
        {
            object data = null;
            if (_Cache.GetItem(GetCacheKey(), out data) == false)
            {
                if (data == null)
                {
                    data = _dbContext.Set<TEntity>().ToList();
                    _Cache.PutItem(GetCacheKey(), data, new string[] { GetCacheKey() }, Cache.NoSlidingExpiration, Cache.NoAbsoluteExpiration);
                }
            }
            return data as List<TEntity>;
        }

        public override TEntity Find(object key)
        {
            var model = All().FirstOrDefault(m => entityKey(m) == key);
            if (model == null)
            {
                model = base.Find(key);
            }
            return model;
        }

        public override TEntity Find(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
        {
            return CachedAll().FirstOrDefault(predicate.Compile());
        }
 

    }
 
}
